﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using myNico.Mode;
using System.Threading;
using System.Windows.Threading;

namespace myNico.view
{
    /// <summary>
    /// W_login.xaml 的交互逻辑
    /// </summary>
    public partial class W_login : Window
    {
        public W_login()
        {
            InitializeComponent();
            txt_UserName.Focus();
            txt_PassWord.KeyDown += new KeyEventHandler(txt_PassWord_KeyDown);
        }

        void txt_PassWord_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btn_login_Click(null, null);
            }
        }

        private void setEnabled(bool flag)
        {
            txt_PassWord.IsEnabled = flag;
            txt_UserName.IsEnabled = flag;
            btn_close.IsEnabled = flag;
            btn_login.IsEnabled = flag;
        }
        private void btn_login_Click(object sender, RoutedEventArgs e)
        {

            //Thread thread = new Thread(new ParameterizedThreadStart(checkLogin));
            //thread.Start("");
     //       this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,(ThreadStart)checkLogin);
            this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)checkLogin);
        }

        private void checkLogin()
        {
            string username, password;
            username = txt_UserName.Text;
            password = txt_PassWord.Password;
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("帐号或者密码不能为空", "登陆错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            app_data.UserName = username;
            app_data.PassWord = password;
            app_data.sysPath = AppDomain.CurrentDomain.BaseDirectory;
            btn_login.Content = "登陆中";
            setEnabled(false);
            if (nicotool.nicovideo.LoginToNicovideo(app_data.UserName, app_data.PassWord))
            {
                
                //MessageBox.Show("ok");
                this.DialogResult = true;
            }
            else
            {
                MessageBox.Show("帐号错误");
                btn_login.Content = "登陆";
                setEnabled(true);
            }
        }
        private void btn_close_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}
